package com.cms.controller.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.cms.entity.Order;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cms.ExcelView;
import com.cms.Feedback;
import com.cms.entity.Brand;
import com.cms.entity.Product;
import com.cms.entity.ProductCategory;
import com.cms.routes.RouteMapping;
import com.cms.util.DBUtils;
import com.cms.util.SystemUtils;
import com.cms.util.export.ExcelProduct;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;

/**
 * Controller - 商品
 * 
 * 
 * 
 */
@RouteMapping(url = "/admin/product")

public class ProductController extends BaseController {
    
    /**
     * 添加
     */
    public void add() {
        setAttr("productCategoryTree", new ProductCategory().dao().findTree());
        setAttr("brands", new Brand().dao().findAll());
        render(getView("product/add"));
    }

    /**
     * 保存
     */
    public void save() {
        Product product = getModel(Product.class, "", true);
        if(StringUtils.isNotBlank(product.getImage())){
        	String image = product.getImage();
        	image = image.replace(SystemUtils.getConfig().getImgUrl(), "");
        	product.setImage(image);
        }
        //商品图片
        String [] productImages = getParaValues("productImages");
        if (ArrayUtils.isNotEmpty(productImages)) {
        	List<String> newproductImages = new ArrayList<>();
        	for(String productImage : productImages){
        		if(StringUtils.isNotBlank(productImage)){
        			productImage = productImage.replace(SystemUtils.getConfig().getImgUrl(), "");
        			newproductImages.add(productImage);
        		}
        	}
            product.setProductImage(JSONArray.toJSONString(newproductImages));
        } else {
            product.setProductImage("[]");
        }
        product.setSn(DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS") + RandomStringUtils.randomNumeric(5));
        product.setCreateDate(new Date());
        product.setModifyDate(new Date());
        product.setHits(0l);
        product.setSales(0l);
        product.save();
        redirect(getListQuery("/admin/product/list"));
    }

    /**
     * 编辑
     */
    public void edit() {
        setAttr("productCategoryTree", new ProductCategory().dao().findTree());
        setAttr("product", new Product().dao().findById(getParaToLong("id")));
        setAttr("brands", new Brand().dao().findAll());
        render(getView("product/edit"));
    }

    /**
     * 更新
     */
    public void update() {
        Product product = getModel(Product.class, "", true);
        if(StringUtils.isNotBlank(product.getImage())){
        	String image = product.getImage();
        	image = image.replace(SystemUtils.getConfig().getImgUrl(), "");
        	product.setImage(image);
        }
        //商品图片
        String [] productImages = getParaValues("productImages");
        if (ArrayUtils.isNotEmpty(productImages)) {
        	List<String> newproductImages = new ArrayList<>();
        	for(String productImage : productImages){
        		if(StringUtils.isNotBlank(productImage)){
        			productImage = productImage.replace(SystemUtils.getConfig().getImgUrl(), "");
        			newproductImages.add(productImage);
        		}
        	}
            product.setProductImage(JSONArray.toJSONString(newproductImages));
        } else {
            product.setProductImage("[]");
        }
        product.setModifyDate(new Date());
        product.update();
        redirect(getListQuery("/admin/product/list"));
    }

    /**
     * 列表
     */
    public void list() {
        Product.Type type = getParaToEnum(Product.Type.class,"type");
        Integer pageNumber = getParaToInt("pageNumber");
        if (pageNumber == null) {
            pageNumber = 1;
        }
        Long brandId = getParaToLong("brandId");
        String name = getPara("name");
        Long productCategoryId = getParaToLong("productCategoryId");
        setAttr("page", new Product().dao().findPage(pageNumber, PAGE_SIZE, productCategoryId,name,type,brandId));
        setAttr("name", name);
        if(type!=null){
            setAttr("type", type.name());
        }
        setAttr("productCategoryId", productCategoryId);
        setAttr("productCategoryTree", new ProductCategory().dao().findTree());
        setAttr("brands", new Brand().dao().findAll());
        setAttr("brandId", brandId);
        render(getView("product/list"));
    }
    
    /**
     * 列表
     */
    public void choose() {
        Integer pageNumber = getParaToInt("pageNumber");
        if (pageNumber == null) {
            pageNumber = 1;
        }
        String name = getPara("name");
        Long productCategoryId = getParaToLong("productCategoryId");
        setAttr("page", new Product().dao().findPage(pageNumber, PAGE_SIZE, productCategoryId,name,null,null));
        setAttr("name", name);
        render(getView("product/choose"));
    }
    
    
    public void upMarket(){
    	 Long ids[] = getParaValuesToLong("ids");
         Db.update("update cms_product set isMarketable=1 where id in("+StringUtils.join(ids,",")+")");
         renderJson(Feedback.success(new HashMap<>()));
    }
    
    public void downMarket(){
    	 Long ids[] = getParaValuesToLong("ids");
         Db.update("update cms_product set isMarketable=0 where id in("+StringUtils.join(ids,",")+")");
         renderJson(Feedback.success(new HashMap<>()));
    }
    
    

    /**
     * 删除
     */
    public void delete() {
        Long ids[] = getParaValuesToLong("ids");
        for (Long id : ids) {
            new Product().dao().deleteById(id);
        }
        renderJson(Feedback.success(new HashMap<>()));
    }
    
    
	/**
     * 修改排序
     */
    public void updateSort(){
        String sortArray = getPara("sortArray");
        JSONArray jsonArray = JSONArray.parseArray(sortArray);
        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Long id = jsonObject.getLong("id");
            Integer sort = jsonObject.getInteger("sort");
            Product product = new Product().dao().findById(id);
            product.setSort(sort);
            product.update();
        }
        renderJson(Feedback.success(new HashMap<>()));
    }

	public void export(){
        Product.Type type = getParaToEnum(Product.Type.class,"type");
    	if(type==null){
            type = Product.Type.SELL;
    	}
        Long brandId = getParaToLong("brandId");
        String name = getPara("name");
        Long productCategoryId = getParaToLong("productCategoryId");
        
        String filterSql = "";
        if(productCategoryId!=null){
            filterSql+=" and productCategoryId="+productCategoryId;
        }
        if(StrKit.notBlank(name)){
            filterSql+=" and name like '%"+name+"%'";
        }
        if(type!=null){
            if(type.ordinal() == Product.Type.SELL.ordinal()){
                filterSql+=" and isMarketable=1";
            }else if(type.ordinal() == Product.Type.SELL_OUT.ordinal()){
                filterSql+=" and stock<=0";
            }else if(type.ordinal() == Product.Type.OFF_SHELF.ordinal()){
                filterSql+=" and isMarketable=0";
            }
        }
        if(brandId!=null){
        	filterSql+=" and brandId="+brandId;
        }
        String orderBySql = DBUtils.getOrderBySql("createDate desc");
        List<Product> products = new Product().dao().find("select * from cms_product where 1=1 "+filterSql+orderBySql);
	    String filename = "商品_" + DateFormatUtils.format(new Date(), "yyyyMM") + ".xls";
	    String[] contents = new String[3];
	    contents[0] = "生成数量" + ": " + products.size();
	    contents[1] = "操作员" + ": " + getCurrentAdmin().getUsername();
	    contents[2] = "生成日期" + ": " + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
	    List<ExcelProduct> data = new ArrayList<>();
	    for(Product product : products){
	    	ExcelProduct excelProduct = new ExcelProduct();
	    	excelProduct.setId(product.getId()+"");
	    	if(product.getProductCategory()!=null){
	    		excelProduct.setProductCategory(product.getProductCategory().getName());
	    	}else{
	    		excelProduct.setProductCategory("");
	    	}
	    	excelProduct.setName(product.getName());
	    	if(product.getBrand()!=null){
	    		excelProduct.setBrand(product.getBrand().getName());
	    	}else{
	    		excelProduct.setBrand("");
	    	}
	    	if(product.getPrice()!=null){
	    		excelProduct.setPrice(product.getPrice().toString());
	    	}else{
	    		excelProduct.setPrice("");
	    	}
	    	if(product.getMarketPrice()!=null){
	    		excelProduct.setMarketPrice(product.getMarketPrice().toString());
	    	}else{
	    		excelProduct.setMarketPrice("");
	    	}
	    	if(product.getCost()!=null){
	    		excelProduct.setCost(product.getCost().toString());
	    	}else{
	    		excelProduct.setCost("");
	    	}
	    	if(product.getIsMarketable()){
	    		excelProduct.setIsMarketable("是");
	    	}else{
	    		excelProduct.setIsMarketable("否");
	    	}
	    	if(product.getStock()!=null){
	    		excelProduct.setStock(product.getStock()+"");
	    	}else{
	    		excelProduct.setStock("");
	    	}
	    	if(StringUtils.isBlank(product.getTag())){
	    		excelProduct.setTag(product.getTag());
	    	}else{
	    		excelProduct.setTag("");
	    	}
	    	excelProduct.setCreateDate(DateFormatUtils.format(product.getCreateDate(), "yyyy-MM-dd"));
	    	data.add(excelProduct);
	    }
	    try {
	        new ExcelView(filename, null, new String[] { "id","productCategory","name","brand","price","marketPrice","cost","isMarketable","stock","tag","createDate" }, new String[] { "ID","商品分类","商品名称","品牌","商品价格","市场价","成本价","是否上架","库存","标签","创建日期"}, null, null, data, contents).buildExcelDocument(getRequest(), getResponse());
	        renderNull();
	    } catch (Exception e) {
	        // TODO Auto-generated catch block
	        e.printStackTrace();
	    }
	}
}
